import axios from 'axios'
import LocalStorage from '@/utils/LocalStorage'
import { useAppsStore } from '@/stores/modules/app'
import router from '@/router'

axios.defaults.baseURL = import.meta.env.VITE_BASEURL
axios.defaults.timeout = import.meta.env.VITE_REQUESTTIMEOUT
axios.defaults.headers.post['Content-Type'] = import.meta.env.VITE_CONTENT_TYPE

axios.interceptors.request.use(
  (config): any => {
    if (config?.url && !config?.url.includes('www.tujigu.top')) {
      config.baseURL = import.meta.env.VITE_BASEURL
      const token = LocalStorage.get(import.meta.env.VITE_TOKEN_LOACTION_NAME)
      if (token) {
        config.headers[import.meta.env.VITE_TOKEN_NAME] = token
      }
    }
    return config
  },
  error => {
    return error
  }
)
// 响应拦截
axios.interceptors.response.use(res => {
  if (res.config?.url && res.config.url.includes('http')) {
    return res
  } else if (res.data.code === 401) {
    const useApp = useAppsStore()
    const { signOut } = useApp
    signOut()
    router.replace('/login')
  }
  return res
})

interface ResType<T> {
  code: number
  data?: T
  message: string
  err?: string
}

interface Http {
  get<T>(url: string, params?: unknown): Promise<ResType<T>>
  post<T>(url: string, params?: unknown): Promise<ResType<T>>
  delete<T>(url: string, params?: unknown, headers?: any): Promise<ResType<T>>
  upload<T>(url: string, params: unknown): Promise<ResType<T>>
  download(url: string): void
}

const http: Http = {
  get(url, params) {
    return new Promise((resolve, reject) => {
      axios
        .get(url, { params })
        .then(res => {
          resolve(res.data)
        })
        .catch(err => {
          reject(err.data)
        })
    })
  },

  post(url, params) {
    return new Promise((resolve, reject) => {
      axios
        .post(url, JSON.stringify(params))
        .then(res => {
          resolve(res.data)
        })
        .catch(err => {
          reject(err.data)
        })
    })
  },

  delete(url, data, headers) {
    return new Promise((resolve, reject) => {
      axios
        .delete(url, {
          data,
          headers
        })
        .then(res => {
          resolve(res.data)
        })
        .catch(err => {
          reject(err.data)
        })
    })
  },

  upload(url: string, file) {
    return new Promise((resolve, reject) => {
      axios
        .post(url, file, {
          headers: { 'Content-Type': 'multipart/form-data' }
        })
        .then(res => {
          resolve(res.data)
        })
        .catch(err => {
          reject(err.data)
        })
    })
  },

  download(url: string): void {
    const iframe: HTMLIFrameElement = document.createElement('iframe')
    iframe.style.display = 'none'
    iframe.src = url
    iframe.onload = function (): void {
      document.body.removeChild(iframe)
    }
    document.body.appendChild(iframe)
  }
}

export default http
